package com.oe.market.modules.base.service;

import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.oe.market.modules.base.model.bean.ServerInfo;
import com.oe.market.modules.base.model.dao.AccountDao;
import com.oe.market.modules.common.utils.Mail;

import java.util.HashMap;
import java.util.Map;

public class MailService {
    Map<String,String> verifyMap = new HashMap<>();

    public static MailService me = new MailService();


    public boolean bindUser(String user, String mail) {
        Digester sha1 = new Digester(DigestAlgorithm.SHA1);
        String verifyCode =  sha1.digestHex(user + ServerInfo.version + ServerInfo.createTime);
        String verifyUrl = ServerInfo.url + "/v1/base/account/bind/mail/"+ user + "/" + verifyCode;
        if (Mail.getInstance().send(mail,"绑定邮箱",verifyUrl)) {
            String value = verifyCode + "," + mail;
            verifyMap.put(user,value);
            return true;
        }
        return false;
    }

    public boolean verifyUser(String user, String verifyCode) {
        String value = verifyMap.get(user);
        if (null == value) {
            return false;
        }
        String[] strings = value.split(",");
        if (strings[0].equals(verifyCode)) {
            // bind email
            String mail = strings[1];
            if (AccountDao.me.updateMail(user,mail)) {
                verifyMap.remove(user);
            }
            return true;
        }
        return false;
    }
}
